﻿using Newtonsoft.Json;
using RobotLib.Constant;
using RobotLib.Dto;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using WebSocket4Net;

namespace RobotLib.IWebSocket
{
	// 声明播放音频委托
	public delegate void PlayAudio(string base64string);
	// 声明发送消息委托
	public delegate void Sender(string message);
	// 声明接收消息委托
	public delegate void Receiver(string message);
	// 开始说话委托
	public delegate void StartTalking();
	// 结束说话
	public delegate void StopTalking();
	// 服务断开委托
	public delegate void Closed();
	// 动作指令
	public delegate void Command(string message);
	// 打开报告
	public delegate void OpenReport(string message);
	// 关闭报告
	public delegate void CloseReport();

	public class IWebSocket
	{
		// 定义websocket
		private WebSocket ws;
		// 定义委托
		public PlayAudio playAudio;
		public Sender sender;
		public Receiver receiver;
		public StartTalking startTalking;
		public StopTalking stopTalking;
		public Closed closed;
		public Command command;
		public OpenReport openReport;
		public CloseReport closeReport;

		public void Start(string url)
		{
			ws = new WebSocket(url);

			// 注册打开连接的回调
			ws.Opened += (sender, e) => {
				Console.WriteLine("WebSocket连接已打开");
				// 发送消息
				ws.Send("Hello from Unity 3D client!");
			};
			// 注册收到消息的回调
			ws.MessageReceived += (sender, e) => {
				Console.WriteLine("收到消息：{0}", e.Message);
				//Receive(e.Message);
			};
			// 注册错误发生的回调
			ws.Error += (sender, e) => {
				Console.WriteLine("发生错误：{0}", e.Exception);
			};
			// 注册关闭连接的回调
			ws.Closed += (sender, e) =>
			{
				Console.WriteLine("WebSocket连接已关闭");
				closed();
			};
			// 启动连接
			ws.Open();
			// 等待用户按下任意键退出
			Console.ReadKey();
			// 关闭连接
			//ws.Close();
		}

		/// <summary>
		/// 关闭连接
		/// </summary>
		private void Close()
		{
			if (ws != null)
			{
				ws.Close();
			}
		}

		/// <summary>
		/// 处理接收消息
		/// </summary>
		/// <param name="message"></param>
		private void Receive(string message)
		{
			var m = JsonConvert.DeserializeObject<MessageDto<string>>(message);
			switch (m.Key)
			{
				case MeatballConstant.START_TALKING:
					startTalking();
					break;
				case MeatballConstant.STOP_TALKING:
					stopTalking();
					break;
				case MeatballConstant.SENDER:
					sender(m.Data);
					break;
				case MeatballConstant.RECEIVER:
					receiver(m.Data);
					break;
				case MeatballConstant.AUDIO:
					playAudio(m.Data);
					break;
				case MeatballConstant.COMMAND:
					if (m.Data.StartsWith(MeatballConstant.COMMAND_TYPE))
					{
						command(m.Data);
					}
					else if (m.Data.StartsWith(MeatballConstant.REPORT))
					{
						if (m.Data.Contains("close"))
						{
							closeReport();
						}
						else
						{
							openReport(m.Data.Replace(MeatballConstant.REPORT, ""));
						}
					}
					else if (m.Data.StartsWith(MeatballConstant.COMMAND_CMD))
					{
						Cmd(m.Data);
					}
					break;
				default:
					break;
			}
		}

		/// <summary>
		/// 执行硬件操作
		/// </summary>
		/// <param name="message"></param>
		private void Cmd(string message)
		{
			message = message.Replace(MeatballConstant.COMMAND_CMD, "");
			string[] text = message.Split(';');

			UdpClient client = new UdpClient();
			IPAddress iPAddress = IPAddress.Parse(text[0]);
			IPEndPoint host = new IPEndPoint(iPAddress, int.Parse(text[1]));
			//
			byte[] messageBytes = Encoding.UTF8.GetBytes(text[2]);
			int result = client.Send(messageBytes, messageBytes.Length, host);
		}
		
		/// <summary>
		/// 播放声音
		/// </summary>
		/// <param name="base64string"></param>
		/*public static void PlayAudio(string base64string)
		{
			// 要播放的Base64字符串
			string base64String = "data:audio/mp3;base64," + base64string;
			// 将Base64字符串转换为byte数组
			byte[] bytes = Convert.FromBase64String(base64String.Split(',')[1]);
			// 使用内存流读取byte数组
			using (MemoryStream stream = new MemoryStream(bytes))
			{
				// 使用Mp3FileReader解码MP3音频
				using (Mp3FileReader reader = new Mp3FileReader(stream))
				{
					// 创建WaveOutEvent实例，用于播放音频
					using (WaveOutEvent output = new WaveOutEvent())
					{
						// 将reader与output绑定
						output.Init(reader);
						// 播放音频
						output.Play();
						// 等待播放结束
						while (output.PlaybackState == PlaybackState.Playing)
						{
							System.Threading.Thread.Sleep(100);
						}
					}
				}
			}
		}*/
	}
}
